#include <func.h>

int main(int argc,char **argv)
{
    ARGS_CHECK(argc,3); //ip加端口
    int socketFd;
    socketFd = socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(socketFd,-1,"socket");
    printf("socket success, socketFd:%d\n",socketFd);

    struct sockaddr_in ser;
    memset(&ser,0,sizeof(ser));
    ser.sin_family = AF_INET;
    ser.sin_port = htons(atoi(argv[2]));
    ser.sin_addr.s_addr = inet_addr(argv[1]);

    int ret ;
    ret = connect(socketFd,(struct sockaddr*)&ser,sizeof(ser));
    ERROR_CHECK(ret,-1,"connect");
    printf("connect success!\n");

    char buf[512] = {0};
    fd_set rdset;
    while(1)
    {
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO,&rdset);//将标准输入和socket设置进select的监视队列
        FD_SET(socketFd,&rdset);
        ret = select(socketFd+1,&rdset,NULL,NULL,NULL);
        if(ret)
        {
            if(FD_ISSET(socketFd,&rdset))//socketFd接口传来数据
            {
                memset(buf,0,sizeof(buf));
                ret = recv(socketFd,buf,sizeof(buf),0);
                if(!ret)//服务器链接断开
                {
                    printf("server is deconnected\n");
                    break;
                }
                else
                {
                    printf("recv: %s\n",buf);
                }
            }
            else
            {
                memset(buf,0,sizeof(buf));
                read(STDIN_FILENO,buf,sizeof(buf));
                send(socketFd,buf,strlen(buf)-1,0);
            }
        }

    }


    close(socketFd);
    return 0;
}

